<script setup lang="ts">
import { onMounted, reactive, ref, toRaw } from 'vue';
import { cloneDeep } from 'lodash-es';
import { zhCN } from 'naive-ui';
import { registerAllModules } from 'handsontable/registry';
import { registerLanguageDictionary, zhCN as zhCNH } from 'handsontable/i18n';
import 'handsontable/styles/handsontable.min.css';
import 'handsontable/styles/ht-theme-main.min.css';
import { HotTable } from '@handsontable/vue3';
import 'handsontable/plugins/contextMenu';
import 'handsontable/plugins/mergeCells';
import { hlCells, hlNormalConfig, hlAfterSetCellMeta } from '../../customMethod';
import SetCellAttributeModal from './modules/SetCellAttributeModal.vue';

interface Props {
  mode: 'editable' | 'write' | 'preview';
  readOnlyColor?: string;
  renderData: {
    rows: string[][];
    mergeCells: App.MergeCellsItem[];
    cellComments: App.CellCommentItem[];
    readOnlyCells: string[];
    cellTypeList: App.CellTypeItem[];
  }
}
const props = withDefaults(defineProps<Props>(), {
  readOnlyColor: '#a3a3a3'
});

const originalData = cloneDeep(props.renderData.rows);
const readOnlyCellsData = cloneDeep(props.renderData.readOnlyCells);
const cellTypeListData = cloneDeep(props.renderData.cellTypeList);


const clickSetCellAttribute = (key: string, options: any) => {
  setCellAttributeModalRef.value.openDialog({
    cell: options,
    originalData,
    readOnlyCellsData,
    cellTypeListData
  });
};

const hotTableRef = ref();
const setCellAttributeModalRef = ref();
const state = reactive({
  flag: false,
  hotSettings: {
    data: originalData,
    ...hlNormalConfig(props.mode, props.renderData.cellComments, props.renderData.mergeCells, clickSetCellAttribute),
    ...hlCells(props.mode, readOnlyCellsData, cellTypeListData),
    // afterSetDataAtCell: (changes, source) => {
    //   console.log(changes);
    //   console.log(source);
    // },
    afterSetCellMeta: (row: number, col: number, key: string, value: any) => hlAfterSetCellMeta(row, col, key, value, readOnlyCellsData)
  }
});

const getTableConfig = () => {
  // console.log(hotTableRef.value.hotInstance);
  // console.log('原始数据');
  // console.log(hotTableRef.value.hotInstance.getData());
  // console.log('合并单元格数据');
  // console.log(hotTableRef.value.hotInstance.getPlugin('mergeCells').mergedCellsCollection.mergedCells);
  const cellComments = [] as any;
  const readOnlyList = [] as any;
  const typeList = [] as any;
  const allCellsMeta = hotTableRef.value.hotInstance.getCellsMeta();
  allCellsMeta.map((item: any) => {
    if (item.comment) {
      cellComments.push({
        row: item.row,
        col: item.col,
        comment: toRaw(item.comment)
      });
    }
    if (item.readOnly) {
      readOnlyList.push(item.row + '-' + item.col);
    }
    if (item.type !== 'text') {
      const obj = {
        row: item.row,
        col: item.col,
        type: item.type,
      }
      const dataMap = {
        autocomplete: {
          source: item.source,
          strict: item.strict
        },
        checkbox: {
          label: {
            position: item.label.position,
            value: item.label.value
          }
        },
        date: {
          dateFormat: item.dateFormat
        },
        dropdown: {
          source: item.source
        }
      }
      if (dataMap.hasOwnProperty(item.type)) {
        typeList.push({
          // @ts-ignore
          ...dataMap[item.type],
          ...obj
        });
      }
    }
  });
  // console.log('批注数据');
  // console.log(cellComments);
  // console.log('只读数据');
  // console.log(readOnlyList);
  // console.log('设置类型单元格数据');
  // console.log(typeList);
  return {
    rows: hotTableRef.value.hotInstance.getData(),
    mergeCells: hotTableRef.value.hotInstance.getPlugin('mergeCells').mergedCellsCollection.mergedCells,
    cellComments,
    readOnlyCells: readOnlyList,
    cellTypeList: typeList
  }
};
const updateCellAttribute = (cellAttribute: any, cellIndex: string) => {
  if (cellIndex) {
    const [startRow, startCol] = cellIndex.split('-');
    const [row, col] = [~~startRow, ~~startCol];
    originalData[row][col] = cellAttribute.content;
    if (cellAttribute.readonly) {
      if (!readOnlyCellsData.includes(cellIndex)) {
        readOnlyCellsData.push(cellIndex);
      }
    } else {
      if (readOnlyCellsData.includes(cellIndex)) {
        readOnlyCellsData.splice(readOnlyCellsData.indexOf(cellIndex), 1);
      }
    }
    if (cellAttribute.type === 'autocomplete') {
      cellTypeListData.map(item => {
        if (item.row === row && item.col === col) {
          item.source = cellAttribute.source;
          item.strict = cellAttribute.strict;
        }
      });
    }
    if (cellAttribute.type === 'checkbox') {
      cellTypeListData.map(item => {
        if (item.row === row && item.col === col) {
          item.label = cellAttribute.label;
        }
      });
    }
    if (cellAttribute.type === 'date') {
      cellTypeListData.map(item => {
        if (item.row === row && item.col === col) {
          item.dateFormat = cellAttribute.dateFormat;
        }
      });
    }
    if (cellAttribute.type === 'dropdown') {
      cellTypeListData.map(item => {
        if (item.row === row && item.col === col) {
          item.source = cellAttribute.source;
        }
      });
    }
  }
  // 强制重新渲染
  hotTableRef.value.hotInstance.render();
};
onMounted(() => {
  registerLanguageDictionary(zhCNH);
  registerAllModules();
  setTimeout(() => {
    state.flag = true;
  }, 200);
});
defineExpose({
  getTableConfig
});
</script>

<template>
  <n-config-provider :locale="zhCN">
    <div v-if="state.flag" class="ht-theme-main-dark-auto">
      <hot-table ref="hotTableRef" :settings="state.hotSettings"></hot-table>
      <set-cell-attribute-modal ref="setCellAttributeModalRef" @click-confirm="updateCellAttribute" />
    </div>
  </n-config-provider>
</template>

<style scoped lang="scss">
 .ht-theme-main-dark-auto{
   :deep() {
     .htDimmed{
       color:v-bind(readOnlyColor)
     }
   }
 }
</style>
